package cn.chinaflame.pagodas.service;

import cn.chinaflame.pagodas.Result.Result;
import cn.chinaflame.pagodas.constant.Sysconst;
import cn.chinaflame.pagodas.dto.PaInvitationDetailDto;
import cn.chinaflame.pagodas.dto.PaInvitationDto;
import cn.chinaflame.pagodas.dto.VwBlessBeinvitedDto;
import cn.chinaflame.pagodas.dto.VwBlessInvitationDto;
import cn.chinaflame.pagodas.entity.*;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.repository.*;
import cn.chinaflame.pagodas.req.PaInvitationReq;
import cn.chinaflame.pagodas.utils.DateTimes;
import cn.chinaflame.pagodas.utils.ParamPreconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.util.List;
import java.util.Map;

/**
 * 邀请service
 *
 * @author bm
 * 2018年1月13日 上午11:27:48
 */
@Service
public class PaInvitationService {
    private final static Logger log = LoggerFactory.getLogger(PaInvitationService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PaMemberService paMemberService;
    @Autowired
    private IdGeneratorService idGeneratorService;
    @Autowired
    private PaInvitationRepository paInvitationRepository;
    @Autowired
    private YwItemRepository ywItemRepository;
    @Autowired
    private PaProductAreaRepository paProductAreaRepository;
    @Autowired
    private PaProductPositionRepository paProductPositionRepository;
    @Autowired
    private PaProductRepository paProductRepository;
    @Autowired
    private PaMemberRepository paMemberRepository;
    @Autowired
    private VwBlessInvitationRepository vwBlessInvitationRepository;
    @Autowired
    private VwBlessBeinvitedRepository vwBlessBeinvitedRepository;
    @Autowired
    private PaProductPointService paProductPointService;

    /**
     * 查询我的邀请
     *
     * @param sourceMemberId -会员id
     * @param sourceOpenid   -微信openid
     * @return
     */
    public List<PaInvitationDto> query(String sourceMemberId, String sourceOpenid) {
        log.info("查询邀请列表sourceMemberId:{},sourceOpenid:{}", sourceMemberId, sourceOpenid);
        ParamPreconditions.checkArgument(!Strings.isNullOrEmpty(sourceMemberId) || !Strings.isNullOrEmpty(sourceOpenid),
                CodeEnum.FAIL.getCode(), "会员id和openid不能同时为空");
        String sql = null;
        if (!Strings.isNullOrEmpty(sourceMemberId))
            sql = "select b.id as blessId,b.success as success,i.target_member_id as targetMemberId,i.target_openid as targetOpenid," +
                    "m.name as targetName,o.id as orderId,r.be_wished_name as beWishedName,r.be_wished_sex as beWishedSex," +
                    "r.be_wished_birthday as beWishedBirthday,r.be_wished_address as beWishedAddress from " +
                    " pa_invitation i,pa_bless b,pa_member m,pa_order o, pa_orderitem r" +
                    " where b.id = i.bless_id and b.source_member_id = m.id and b.order_id = o.id and r.order_id = o.id and i.source_member_id=" + sourceMemberId;
        else
            sql = "select b.id as blessId,b.success as success,i.target_member_id as targetMemberId,i.target_openid as targetOpenid," +
                    "m.name as targetName,o.id as orderId,r.be_wished_name as beWishedName,r.be_wished_sex as beWishedSex," +
                    "r.be_wished_birthday as beWishedBirthday,r.be_wished_address as beWishedAddress from " +
                    " pa_invitation i,pa_bless b,pa_member m,pa_order o, pa_orderitem r" +
                    " where b.id = i.bless_id and b.source_member_id = m.id and b.order_id = o.id and r.order_id = o.id and i.source_openid=" + sourceOpenid;
        List<PaInvitationDto> result = jdbcTemplate.queryForList(sql, PaInvitationDto.class);
        return result;
    }

    public List<VwBlessInvitationDto> queryDetail2(String memberId, String openid, String mobile, String invitationId) {
        log.info("查询邀请详情列表【service】memberId:{},openid:{},mobile:{},invitationId:{}", memberId, openid, mobile, invitationId);
        PaMember member = paMemberService.findOne(memberId, mobile, openid, null, null, null);
        ParamPreconditions.checkNotNull(member, CodeEnum.FAIL.getCode(), "未找到会员信息");
        List<VwBlessInvitation> entityList = vwBlessInvitationRepository.findAll((Specification<VwBlessInvitation>) (root, query, cb) -> {
            List<Predicate> list = Lists.newArrayList();
//				list.add(cb.equal(root.get("status").as(String.class), Sysconst.INVITATION_STATUS_SUCCESS));
            list.add(cb.equal(root.get("sourceMemberId").as(String.class), member.getId()));
            if (!Strings.isNullOrEmpty(invitationId))
                list.add(cb.equal(root.get("invitationId").as(String.class), invitationId));
            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        });
        List<VwBlessInvitationDto> dtos = Lists.newArrayList();
        for (int i = 0; i < entityList.size(); i++) {
            VwBlessInvitationDto dto = new VwBlessInvitationDto();
            BeanUtils.copyProperties(entityList.get(i), dto);
            YwItem item = ywItemRepository.findOne(entityList.get(i).getItemId());
            ParamPreconditions.checkNotNull(item, CodeEnum.FAIL.getCode(), "未找到项目");
            PaProduct product = paProductRepository.findOne(entityList.get(i).getProductId());
            ParamPreconditions.checkNotNull(product, CodeEnum.FAIL.getCode(), "未找到商品信息");
            dto.setProductName(product.getName());
            dto.setItemName(item.getName());
            dtos.add(dto);
        }
        return dtos;
    }

    public List<VwBlessBeinvitedDto> queryBeinvitedDetail2(String memberId, String openid, String mobile) {
        log.info("查询被邀请详情列表【service】memberId:{},openid:{},mobile:{}", memberId, openid, mobile);
        PaMember member = paMemberService.findOne(memberId, mobile, openid, null, null, null);
        ParamPreconditions.checkNotNull(member, CodeEnum.FAIL.getCode(), "未找到会员信息");
        List<VwBlessBeinvited> entityList = vwBlessBeinvitedRepository.findAll((Specification<VwBlessBeinvited>) (root, query, cb) -> {
            List<Predicate> list = Lists.newArrayList();
//				list.add(cb.equal(root.get("status").as(String.class), Sysconst.INVITATION_STATUS_SUCCESS));
            list.add(cb.equal(root.get("memberId").as(String.class), member.getId()));
            Predicate[] p = new Predicate[list.size()];
            return cb.and(list.toArray(p));
        });
        List<VwBlessBeinvitedDto> dtos = Lists.newArrayList();
        for(int i=0;i<entityList.size();i++){
        	VwBlessBeinvited po = entityList.get(i);
        	VwBlessBeinvitedDto dto = new VwBlessBeinvitedDto();
        	BeanUtils.copyProperties(po, dto);
        	String nowTime = DateTimes.nowDateTime();
            int wishStatus = 1;
            wishStatus = dto.getEndTime().compareTo(nowTime);
            dto.setWishStatus(wishStatus);
            dtos.add(dto);
        }
        return dtos;
    }

    public List<Map<String, Object>> queryDetailByStatisticByInvitationId(String invitationId) {
        log.info("根据邀请id统计邀请详情invitationId:{}", invitationId);
        ParamPreconditions.checkNotEmpty(invitationId, CodeEnum.FAIL.getCode(), "邀请id不能为空");
        String sql = "select count(*) as personCount,IFNULL(sum(detail.term),0) as productNumber " +
                "from vw_bless_detail detail,pa_invitation invitation " +
                "where detail.invitation_id = invitation.id and detail.status in(" + Sysconst.BLESS_STATUS_USING + "," + Sysconst.BLESS_STATUS_FINISH + ") and invitation.id=" + invitationId;
        List<Map<String, Object>> dtos = jdbcTemplate.queryForList(sql);
        return dtos;
    }

    public List<Map<String, Object>> queryDetailByStatisticByOpenid(String openid) {
        log.info("根据openid统计邀请详情openid:{}", openid);
        ParamPreconditions.checkNotEmpty(openid, CodeEnum.FAIL.getCode(), "openid不能为空");
        String sql = "select count(*) as personCount,IFNULL(sum(detail.term),0) as productNumber " +
                "from vw_bless_detail detail,pa_invitation invitation " +
                "where detail.invitation_id = invitation.id and detail.status in(" + Sysconst.BLESS_STATUS_USING + "," + Sysconst.BLESS_STATUS_FINISH + ") and invitation.source_openid=" + openid;
        List<Map<String, Object>> dtos = jdbcTemplate.queryForList(sql);
        return dtos;
    }

    /**
     * 添加邀请信息
     *
     * @param req
     * @return
     */
    public Object add(PaInvitationReq req) {
        log.info("添加邀请信息req:{}", req);
        req.check();
        PaMember member = paMemberService.findOne(req.getMemberId(), req.getMobile(), req.getOpenid(), null, null, null);
        if (member == null) {
            String newMemberId = idGeneratorService.generateMemberId();
            PaMember newMember = new PaMember();
            newMember.setId(newMemberId);
            newMember.setOpenid(req.getOpenid());
            newMember.setMobile(req.getMobile());
            newMember.setRegistFlg(Sysconst.REGIST_FALSE);
            member = paMemberRepository.saveAndFlush(newMember);
        }
        PaInvitation invitation = new PaInvitation();
        String invitationId = idGeneratorService.generateInvitationId();
        invitation.setId(invitationId);
        invitation.setSourceMemberId(member.getId());
        invitation.setSourceOpenid(member.getOpenid());
        invitation.setSourceMobile(member.getMobile());
        invitation.setTargetMemberId(null);
        invitation.setTargetOpenid(null);
        invitation.setTargetMobile(null);
        //商品流程变动，暂时注释
//        Result result = (Result)paProductPointService.getPaProductPointByProductId(req.getProductId());
//        if (result.getCode().equals("OK")) {
//            PaProductPoint paProductPoint = (PaProductPoint)result.getData();
//            invitation.setProductAreaId(paProductPoint.getAreaId());
//            invitation.setProductPositionId(paProductPoint.getPositionId());
//        }else {
//            return Result.create("FALSE",result.getMsg());
//        }

        invitation.setProductId(req.getProductId());
        invitation.setItemId(req.getItemId());

        invitation.setBeWishedName(req.getBeWishedName());
        ;
        invitation.setBeWishedSex(req.getBeWishedSex());
        invitation.setBeWishedBirthday(req.getBeWishedBirthday());
        invitation.setBeWishedMobile(req.getBeWishedMobile());
        invitation.setBeWishedAddress(req.getBeWishedAddress());
        invitation.setBeWishedMemo(req.getBeWishedMemo());
        invitation.setCreatetime(DateTimes.nowDateTime());
        invitation.setUpdatetime(DateTimes.nowDateTime());
        paInvitationRepository.saveAndFlush(invitation);
        return Result.create(invitationId);
    }

    public PaInvitationDetailDto queryById(String invitaionId) {
        log.info("查询邀请详情invitationId:{}", invitaionId);
        ParamPreconditions.checkNotEmpty(invitaionId, CodeEnum.FAIL.getCode(), "邀请id不能为空");
        PaInvitation invitation = paInvitationRepository.findOne(invitaionId);
        ParamPreconditions.checkNotNull(invitation, CodeEnum.FAIL.getCode(), "未找到邀请信息");
        YwItem item = ywItemRepository.getOne(invitation.getItemId());
//        PaProductArea area = paProductAreaRepository.getOne(invitation.getProductAreaId());
//        PaProductPosition position = paProductPositionRepository.getOne(invitation.getProductPositionId());
        PaProduct product = paProductRepository.getOne(invitation.getProductId());
        PaMember member = paMemberRepository.findOne(invitation.getSourceMemberId());
        ParamPreconditions.checkNotNull(member, CodeEnum.FAIL.getCode(), "还不是会员");
        PaInvitationDetailDto dto = new PaInvitationDetailDto();
        dto.setOpenid(member.getOpenid());
        dto.setMobile(member.getMobile());
        dto.setMemberId(member.getId());
        dto.setNickName(member.getNickName());
        dto.setNickSex(member.getNickSex());
        dto.setNickLanguage(member.getNickLanguage());
        dto.setNickCity(member.getNickCity());
        dto.setNickProvince(member.getNickProvince());
        dto.setNickCountry(member.getNickCountry());
        dto.setNickHeadimgurl(member.getNickHeadimgurl());

        dto.setItemId(item.getId());
        dto.setItemName(item.getName());
        dto.setProductId(product.getId());
        dto.setProductName(product.getName());
        //商品流程改动，暂时注释
//        dto.setProductAreaId(area.getId());
//        dto.setProductAreaName(area.getName());
//        dto.setProductPositionId(position.getId());
//        dto.setProductPositionName(position.getName());
        dto.setBeWishedName(invitation.getBeWishedName());
        dto.setBeWishedSex(invitation.getBeWishedSex());
        dto.setBeWishedBirthday(invitation.getBeWishedBirthday());
        dto.setBeWishedMemo(invitation.getBeWishedMemo());
        dto.setBeWishedMobile(invitation.getBeWishedMobile());
        dto.setBeWishedAddress(invitation.getBeWishedAddress());
        return dto;
    }
}
